import React, { useContext, useRef } from 'react';
import { Pressable, View, Text } from 'react-native';
import { useCheckbox, useCheckboxGroupItem, useCheckboxGroup } from '@react-native-aria/checkbox';
import { useToggleState } from '@react-stately/toggle';
import { useCheckboxGroupState } from "@react-stately/checkbox";
import { useFocusRing } from '@react-native-aria/focus';
let CheckboxGroupContext = React.createContext<any>(null);


export function CheckboxGroup(props: any) {
    let { children, label } = props;
    let state = useCheckboxGroupState(props);
    let { groupProps, labelProps } = useCheckboxGroup(props, state);

    return (
        <View 
            {...groupProps} 
            style={{ flexDirection: 'column', alignItems: 'flex-start' }}
            importantForAccessibility="no" // 防止整个组被屏幕朗读识别
        >
            {label && (
                <Text 
                    {...labelProps} 
                    style={{marginBottom: 10, fontWeight: 'bold'}}
                    accessibilityRole="header"
                >
                    {label}
                </Text>
            )}
            {/* 水平排列的复选框容器 */}
            <View 
                style={{ flexDirection: 'row', flexWrap: 'wrap' }}
                importantForAccessibility="no" // 防止容器被屏幕朗读识别
            >
                <CheckboxGroupContext.Provider value={state}>
                    {children}
                </CheckboxGroupContext.Provider>
            </View>
        </View>
    );
}

export function Checkbox(props: any) {
    let groupState = useContext(CheckboxGroupContext);
    let inputRef = useRef(null);
    let { isFocusVisible, focusProps } = useFocusRing();

    let { inputProps } = groupState ? useCheckboxGroupItem(
        {
            ...props,
            isRequired: props.isRequired,
            validationState: props.validationState,
        },
        groupState,
        inputRef
    ) : useCheckbox(props, useToggleState(props), inputRef);

    // 获取可访问性标签
    const getAccessibilityLabel = () => {
        if (props.accessibilityLabel) return props.accessibilityLabel;
        
        // 尝试从子元素中提取文本
        let labelText = "";
        React.Children.forEach(props.children, (child) => {
            if (typeof child === "string") {
                labelText += child;
            } else if (child && child.props && child.props.children) {
                React.Children.forEach(child.props.children, (grandChild) => {
                    if (typeof grandChild === "string") {
                        labelText += grandChild;
                    }
                });
            }
        });
        
        return labelText || "复选框";
    };

    const accessibilityLabel = getAccessibilityLabel();
    const isChecked = inputProps.checked || false;

    return (
        <View 
            style={[
                isFocusVisible ? { 
                    borderWidth: 2, 
                    borderColor: '#0066cc',
                    borderRadius: 4,
                    margin: 2
                } : {},
                { marginRight: 15 }
            ]}
            importantForAccessibility="yes" // 确保此复选框对屏幕朗读可见
        >
            <Pressable 
                {...inputProps} 
                {...focusProps}
                accessible={true}
                accessibilityRole="checkbox"
                accessibilityState={{ checked: isChecked }}
                accessibilityLabel={accessibilityLabel}
                accessibilityHint={isChecked ? "已选中，双击切换" : "未选中，双击切换"}
                onPress={(event) => {
                    // 手动触发点击事件
                    if (inputProps.onPress) {
                        inputProps.onPress(event);
                    }
                }}
                style={{ flexDirection: 'row', alignItems: 'center' }}
            >
                {/* 复选框图标 */}
                <View 
                    style={{ 
                        width: 24, 
                        height: 24, 
                        borderWidth: 2, 
                        borderColor: isChecked ? '#007AFF' : '#666',
                        borderRadius: 4,
                        justifyContent: 'center',
                        alignItems: 'center',
                        marginRight: 8,
                        backgroundColor: isChecked ? '#007AFF' : 'transparent'
                    }}
                    importantForAccessibility="no" // 防止图标被单独识别
                >
                    {isChecked && (
                        <Text 
                            style={{color: 'white', fontSize: 16, fontWeight: 'bold'}}
                            importantForAccessibility="no"
                        >
                            ✓
                        </Text>
                    )}
                </View>
                {/* 标签文本 - 包含在可访问元素内 */}
                {props.children}
            </Pressable>
        </View>
    );
}

const CheckboxExample = (props: any) => {
    const [state, setCheckbox] = React.useState([]);
    const { setState } = props;

    return (
        <View accessible={false} importantForAccessibility="no">
            <CheckboxGroup
                label="兴趣爱好："
                value={state}
                onChange={(val: any) => {
                    setCheckbox(val);
                    setState(true);
                }}
            >
                <Checkbox value="soccer" accessibilityLabel="足球">
                    <Text importantForAccessibility="no">足球</Text>
                </Checkbox>
                <Checkbox value="baseball" accessibilityLabel="棒球">
                    <Text importantForAccessibility="no">棒球</Text>
                </Checkbox>
                <Checkbox value="basketball" accessibilityLabel="篮球">
                    <Text importantForAccessibility="no">篮球</Text>
                </Checkbox>
            </CheckboxGroup>
        </View>
    );
};

export default CheckboxExample;